
const { ccclass, property } = cc._decorator;

@ccclass
export default class LoadUtil {
    private static spriteAry: { url: string, sprite: cc.Sprite }[] = []
    public static loadImg(url: string, sprite: cc.Sprite, useWx: boolean = false) {
        if (!url || url == "" || url == undefined || !sprite) {
            console.error(`url / sprite :`, url, sprite)
            return;
        }
        // if (useWx && cc.sys.platform != cc.sys.WECHAT_GAME)
        //     return;
        LoadUtil.changeUrl(url, sprite)
        if (cc.sys.platform === cc.sys.WECHAT_GAME && useWx) {
            LoadUtil.wxLoad(url, sprite)
        }
        else {
            LoadUtil.loadUrl(url, sprite)
        }
    }

    private static wxLoad(url: string, sprite: cc.Sprite) {
        let image = window["wx"].createImage();
        image.onload = () => {
            let texture = new cc.Texture2D();
            texture.initWithElement(image);
            texture.handleLoadedTexture();
            if (this.hasUrl(url, sprite) && sprite && sprite.node && sprite.node.isValid) {
                sprite.spriteFrame = new cc.SpriteFrame(texture);
                this.delSp(url, sprite)
            }
        };
        image.src = url;
    }
    private static loadUrl(url: string, sprite: cc.Sprite) {
        cc.loader.load(url, (err, res) => {
            if (err) {
                return;
            }
            if (this.hasUrl(url, sprite) && sprite && sprite.node && sprite.node.isValid) {
                sprite.spriteFrame = new cc.SpriteFrame(res);
                this.delSp(url, sprite)
            }
        });
    }

    private static changeUrl(url: string, sprite: cc.Sprite) {
        for (let i in this.spriteAry) {
            if (this.spriteAry[i].sprite == sprite) {
                this.spriteAry[i].url = url;
                return
            }
        }
        this.spriteAry.push({ url, sprite })
    }

    private static hasUrl(url: string, sprite: cc.Sprite) {
        for (let i in this.spriteAry) {
            if (this.spriteAry[i].url == url && this.spriteAry[i].sprite == sprite) {
                return true;
            }
        }
        return false;
    }

    private static delSp(url: string, sprite: cc.Sprite) {
        for (let i = 0; i < this.spriteAry.length; i++) {
            if (this.spriteAry[i].url == url && this.spriteAry[i].sprite == sprite) {
                this.spriteAry.splice(i, 1)
            }
        }
        return false;
    }
}
